<template>
	<common-card type="form" :title="cardTitle" :loading="loading">
		<el-form ref="form" size="medium" :model="formData" :rules="formRules" :validate-on-rule-change="false">
			<el-form-item label="课题名称" prop="name">
				<el-input v-model="formData.name" placeholder="输入课题名称"></el-input>
			</el-form-item>
			<el-form-item label="课题类型" prop="type">
				<el-radio-group v-model="formData.type" v-removeAriaHidden>
					<el-radio v-for="(item, index) in dictEnums['PROJECT_TYPE']" :key="index" :label="item.value">{{ item.msg }}</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="研究领域" prop="sector">
				<el-radio-group v-model="formData.sector" @change="handleSectorChange" v-removeAriaHidden>
					<el-radio v-for="(item, index) in studySectorData" :key="index" :label="item.name">{{ item.name }}</el-radio>
					<el-radio :label="0">
						<span>其他</span>
						<template v-if="formData.sector === 0">
							<el-input v-model="otherSector" placeholder="输入研究领域"></el-input>
						</template>
					</el-radio>
				</el-radio-group>
			</el-form-item>
			<template v-if="twoSectorData.length > 0">
				<el-form-item label="二级领域" prop="filed4">
					<el-radio-group v-model="formData.filed4" v-removeAriaHidden>
						<el-radio v-for="(item, index) in twoSectorData" :key="index" :label="item.name">{{ item.name }}</el-radio>
					</el-radio-group>
				</el-form-item>
			</template>
			<el-form-item label="测量技术" prop="measureList">
				<el-checkbox-group v-model="formData.measureList">
					<el-checkbox v-for="(item, index) in measuringData" :key="index" :label="item.name">{{ item.name }}</el-checkbox>
				</el-checkbox-group>
			</el-form-item>
			<el-form-item label="强磁场PI" prop="piList">
				<person-select v-model="formData.piList" :data="principalData" placeholder="请选择强磁场PI" multiple></person-select>
			</el-form-item>
			<el-form-item label="申请人">{{ userInfo.username }}</el-form-item>
			<el-form-item label="合作者 :(有强磁场经验或相关学科带头人合作者可增大课题通过的概率)" class="entire" prop="collaList">
				<user-select ref="user" v-model="formData.collaList" :list="userListData"></user-select>
			</el-form-item>
			<el-form-item label="相关经费信息" class="entire" prop="fundsList">
				<fund-select ref="fund" v-model="formData.fundsList"></fund-select>
			</el-form-item>
			<el-form-item label="课题申请文件模板">
				<el-button type="text" class="download" @click="handleDownloadTemp(1)">模板文件</el-button>
			</el-form-item>
			<el-form-item label="课题申请文件上传" prop="fileJson">
				<gx-file-uploader type="4" v-model="formData.fileJson"></gx-file-uploader>
			</el-form-item>
		</el-form>
		<sign-board title="提交课题申请" v-model="signDialog" @finish="handleSignFinish">
			<template slot="body">本人担保以上课题相关信息属实且经过本人审核认可（签字人必须是课题负责人）</template>
		</sign-board>
		<template slot="button">
			<template v-if="userRole === 'member'">
				<el-button type="success" icon="sw-icon-btn-save" :loading="saveLoading" @click="handleSaveData()">保存</el-button>
			</template>
			<el-button type="warning" icon="sw-icon-btn-share" :loading="submitLoading" :disabled="btnDisabled" @click="handleSubmitData()">提交</el-button>
		</template>
	</common-card>
</template>

<script>
import mixins from './mixins';
import signBoard from '../sign';
import fundSelect from './fund';
import formMixins from '../formMixins';
import commonCard from '../commonCard';
import { topicDetail, addedTopic, updateTopic, managerUpdateTopic } from '@/api/business/tbTopic';
export default {
	mixins: [mixins, formMixins],
	components: { commonCard, signBoard, fundSelect },
	data() {
		return {
			formRules: {
				name: [{ required: true, message: '请输入课题名称', trigger: 'blur' }],
				type: [{ required: true, message: '请选择课题类型', trigger: 'change' }],
				sector: [{ required: true, message: '请选择研究领域', trigger: 'change' }],
				filed4: [{ required: true, message: '请选择二级领域', trigger: 'change' }],
				piList: [{ required: true, message: '请选择强磁场PI', trigger: 'change' }],
				measureList: [{ required: true, message: '请选择测量技术', trigger: 'change' }],
				collaList: [{ required: true, message: '请添加合作者', trigger: 'change' }],
				fundsList: [{ required: true, message: '请添加费用信息', trigger: 'change' }],
				fileJson: [{ required: true, message: '请上传课题申请文件', trigger: 'change' }]
			},
			otherSector: '',
			signDialog: false
		};
	},
	computed: {
		cardTitle() {
			return this.addOrEdit ? '新增课题申请' : '修改课题申请';
		},
		twoSectorData() {
			let data = this.studySectorData.find((item) => item.name === this.formData.sector);
			return !data ? [] : !data.children ? [] : data.children;
		},
		userListData() {
			return this.dictEnums['PARTICIPATE_WAY'] || [];
		}
	},
	watch: {
		dataId: {
			async handler(id) {
				this.btnDisabled = false;
				if (!id) return false;
				this.loading = true;
				await this.getDataDetail(id);
				this.$nextTick(() => {
					this.$refs['form'].clearValidate();
				});
			},
			immediate: true
		}
	},
	methods: {
		//获取数据详情
		async getDataDetail(id) {
			let result = await topicDetail(id).then((res) => res.data);
			this.loading = false;
			if (result.code === '0') {
				this.formData = this.formatEchoData(this.$detailData(result.data));
			}
		},

		//格式化回显数据
		formatEchoData(data) {
			this.$set(data, 'piList', this.returnCheckedPiData(data.piList || []));
			this.$set(data, 'fundsList', this.returnCheckedFund(data.fundsList || []));
			this.$set(data, 'collaList', this.returnCheckedPerson(data.collaList || []));
			this.$set(data, 'measureList', this.returnCheckedMeasure(data.measureList || []));
			if (!!data.sector && !this.studySectorData.some((n) => n.name === data.sector)) {
				this.otherSector = data.sector;
				this.$set(data, 'sector', 0);
			}
			return data;
		},

		handleSectorChange(data) {
			this.$set(this.formData, 'filed4', '');
			this.$nextTick(() => {
				this.$refs['form'].clearValidate();
			});
		},

		//保存数据
		handleSaveData() {
			let params = ['name', 'type'];
			this.saveLoading = true;
			this.handleSaveFormData(params);
		},

		//提交数据
		handleSubmitData() {
			this.$refs['form'].validate(async (valid) => {
				let userVaild = await this.$refs['user'].validChildForm();
				let fundValid = await this.$refs['fund'].validChildForm();
				if (!valid || !userVaild || !fundValid) return false;
				if (this.userRole === 'manager') {
					this.submitLoading = true;
					this.managerUpdateData();
				} else {
					if (this.formData.type !== '2') {
						this.signDialog = true;
					} else {
						this.formData['isSave'] = '1';
						this.submitLoading = true;
						this.submitFormRequest();
					}
				}
			});
		},

		//签字
		async handleSignFinish(data) {
			this.formData['filed5'] = data.id;
			this.formData['isSave'] = '1';
			this.submitLoading = true;
			this.submitFormRequest();
		},

		//格式化表单参数
		formatFormParams() {
			let params = this.$lodash.cloneDeep(this.formData);
			if (!!params.fileJson && this.$isJSON(params.fileJson)) {
				let fileJsons = JSON.parse(params.fileJson);
				if (Array.isArray(fileJsons) && fileJsons.length > 0) {
					params['filed2'] = fileJsons[0].id;
				}
			}
			if (params.sector === 0) {
				params['sector'] = this.otherSector;
			}
			params['piList'] = params.piList.map((n) => ({ piId: n }));
			params['measureList'] = params.measureList.map((n) => ({ piId: n }));
			return params;
		},

		//提交表单请求
		async submitFormRequest() {
			let params = this.formatFormParams();
			let callFunction = eval(this.addOrEdit ? addedTopic : updateTopic);
			let result = await callFunction(params).then((res) => res.data);
			this.saveLoading = false;
			this.submitLoading = false;
			if (result.code === '0') {
				this.btnDisabled = true;
				this.$showCustomMessage('success', `${this.cardTitle}成功`);
				this.$router.back();
			}
		},

		//管理员修改请求
		async managerUpdateData() {
			let params = this.formatFormParams();
			let result = await managerUpdateTopic(params).then((res) => res.data);
			this.submitLoading = false;
			if (result.code === '0') {
				this.btnDisabled = true;
				this.$showCustomMessage('success', `${this.cardTitle}成功`);
				this.$router.back();
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.common_project_form {
}
</style>
